package com.acme.iolab.filesend;


import com.acme.iolab.filesend.io.IOFileServer;
import com.acme.iolab.filesend.nio.NIOFileServer;

import java.io.IOException;

public abstract class FileServer {


    private final static String FILE_PATH_TEMPLATE = "F:\\FileFolder\\data_${version}";
    protected int port;

    public FileServer(int port) throws IOException {
        this.port = port;
    }

    public static void main(String[] args) throws IOException {
        String type = "-io";
        FileServer server;
        switch (type) {
            case "-io":
                server = new IOFileServer(ConnectionSettings.PORT);
                break;
            case "-nio":
                server = new NIOFileServer(ConnectionSettings.PORT);
                break;
            default:
                System.out.println("Incorrect argument, required -io | -nio");
                return;
        }
        server.startServer(FILE_PATH_TEMPLATE);
    }

    public void startServer(final String filePrefix) throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int connects = 0;
                while (true) {
                    try {
                        process(filePrefix.replace("${version}", ++connects + ""));
                    } catch (IOException e) {
                        System.out.println("Error receiving file: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }, "Server thread").start();
    }

    public abstract void process(String savePath) throws IOException;

}
